<template>
  <view class="create-task-container">
    <!-- 基础信息 -->
    <view class="section">
      <view class="section-title">基础信息</view>
      <view class="section-nr">
  
  <!-- 供应商 -->
   
  <!-- 单据类型 -->
      <view class="form-item">
        <text class="label">单据类型：</text>
        <picker 
          class="picker" 
          mode="selector" 
          :range="taskTypeOptions" 
          @change="onTaskTypeChange"
          :value="taskTypeIndex"
        >
          <view class="picker-content">
            <text class="picker-text">{{ taskTypeOptions[taskTypeIndex] || '请选择单据类型' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      
      <!-- 供应商选择 -->
      <view class="form-item">
        <text class="label">供应商：</text>
        <view class="picker-content">
          <text class="picker-text">{{ supplierOptions[supplierIndex] || '暂无供应商' }}</text>
        </view>
      </view>
      
      <!-- 配送仓点 - 仅在任务类型为"履约出库"且选择了供应商时显示 -->
      <view class="form-item" v-if="showWarehouse && supplierIndex !== ''">
        <text class="label">配送仓点：</text>
        <picker 
          class="picker" 
          mode="selector" 
          :range="warehouseOptions" 
          @change="onWarehouseChange"
          :value="warehouseIndex"
        >
          <view class="picker-content">
            <text class="picker-text">{{ warehouseOptions[warehouseIndex] || '请选择配送仓点' }}</text>
            <text class="picker-arrow">></text>
          </view>
        </picker>
      </view>
      
      <!-- 备注 -->
      <view class="form-item">
        <text class="label">备注：</text>
        <input 
          class="input" 
          type="text" 
          placeholder="请输入" 
          v-model="remark"
        />
      </view>
      </view>
   
    </view>
    
    <!-- 商品信息 -->
    <view class="section">
      <view class="section-title">
        <text>商品信息</text>
        <text 
          class="add-product-btn" 
          @click="handleAddProduct"
          :class="{ 'add-product-btn-disabled': supplierIndex === '' }"
        >添加商品</text>
      </view>
      
      <!-- 商品列表为空时的提示 -->
      <view class="empty-products" v-if="productList.length === 0">
        <text class="empty-text">当前无商品，请添加商品</text>
      </view>
      
      <!-- 商品列表 -->
       <view class="product-list" v-else>
        <!-- 商品卡片 -->
        <view 
          class="product-card" 
          v-for="(product, index) in filteredProductList" 
          :key="product.rowid"
        >
          <!-- 描述区域 -->
          <view class="product-info">
            <text class="product-name">{{ product['6879f59d8371cd243659b75c'] }}</text>
            <text class="product-code">商品条码：{{ product['68831f272430e5add306b057'] }}</text>
            <text class="product-spec">箱规：{{ product['68831f272430e5add306b059'] || '-' }} 件/箱</text>
            <text class="available-stock">可用库存：{{ product['689160b5f6303e511c9a768b'] || 0 }}</text>
            
            <!-- 商品批次和计划出库数量 -->
            <view class="product-batch-quantity">
              <view class="batch-input-wrapper">
                <text class="batch-label">商品批次：</text>
                <picker 
                  class="batch-picker" 
                  mode="selector" 
                  :range="getProductBatchOptions(product).map(item => item.batchName)" 
                  @change="(e) => onBatchChange(e, product)"
                  @click="() => console.log('批次选择器被点击', product)"
                  :value="getBatchIndex(product)"
                  :disabled="!hasAvailableBatches(product)"
                >
                  <view class="picker-content" :class="{ 'picker-disabled': !hasAvailableBatches(product) }">
                    <text class="picker-text" :class="{ 'picker-text-disabled': !hasAvailableBatches(product) }">
                      {{ product.batch || (hasAvailableBatches(product) ? '请选择批次' : '暂无可用批次') }}
                    </text>
                    <text class="picker-arrow" :class="{ 'picker-arrow-disabled': !hasAvailableBatches(product) }">></text>
                  </view>
                </picker>
              </view>
              <view class="batch-stock-info" v-if="product.batch">
                <text class="batch-stock-label">批次可用库存：</text>
                <text class="batch-stock-value">{{ product.batchCount }}</text>
              </view>
              <view v-if="!hasAvailableBatches(product) && !product.batch" class="batch-tip">
                <text class="batch-tip-text">该商品暂无可用批次库存，请检查供应商或商品信息</text>
              </view>
              <view class="quantity-input-wrapper">
                <text class="quantity-label">计划出库数量：</text>
                <view class="quantity-input-container">
                  <input 
                    class="quantity-input" 
                    :class="{ 'quantity-input-error': isQuantityExceedingStock(product) }"
                    type="number" 
                    placeholder="请输入数量" 
                    v-model.number="product.plannedQuantity"
                  />
                  <view v-if="isQuantityExceedingStock(product)" class="quantity-error-tip">
                    <text class="quantity-error-text">计划出库数量不能大于批次可用库存</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="product-actions">
            <button class="delete-btn" @click="handleDeleteProduct(productList.indexOf(product))">删除</button>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="filteredProductList.length === 0">
          <text class="empty-text">{{ productList.length === 0 ? '暂无商品数据' : '暂无可用批次的商品' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-actions">
      <button 
        class="save-btn" 
        :class="{ 'save-btn-disabled': isSaveDisabled }"
        :disabled="isSaveDisabled"
        @click="handleSave"
      >
        保存任务
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch} from 'vue'
import http from '../../../utils/request'
import { useUserStore } from '../../../store/user'
import { useTaskStore } from '../../../store/task'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'
import { callWorkflowListAPI, callWorkflowAPI } from '../../../utils/workflow'

const userStore = useUserStore()
const taskStore = useTaskStore()

// 选择的供应商rowid
const supplierRowid = ref('')

// 批次库存选项
const batchInventoryOptions = ref([])

// 任务类型选项
const taskTypeOptions = ref(['履约出库', '自提出库', '残品出库', '差异出库'])
const taskTypeIndex = ref('')

// 配送仓点选项
const warehouseOptions = ref([])
const warehouseIndex = ref('')
const allDistributionWarehouses = ref([]) // 存储完整的配送仓点数据（包含关联供应商信息）

// 供应商选项
const supplierOptions = ref([])
const supplierIndex = ref('')
// 供应商数据（包含rowid和名称）
const supplierData = ref([])

// 备注
const remark = ref('')

// 商品列表
const productList = ref([])



// 计算属性：是否显示配送仓点
const showWarehouse = computed(() => {
  const selectedType = taskTypeOptions.value[taskTypeIndex.value]
  return selectedType === '履约出库'
})

// 计算属性：保存按钮是否应该禁用
const isSaveDisabled = computed(() => {
  // 任务类型未选择
  if (taskTypeIndex.value === '') {
    uni.showToast({
      title: '请选择任务类型',
      icon: 'none'
    })
    return true
  }
  
  // 供应商未选择
  if (supplierIndex.value === '') {
    uni.showToast({
      title: '请选择供应商',
      icon: 'none'
    })
    return true
  }
  
  // 商品列表为空 或 过滤后没有可用批次的商品
  if (filteredProductList.value.length === 0) {
    uni.showToast({
      title: '请添加商品并选择可用批次',
      icon: 'none'
    })
    return true
  }
  
  const selectedType = taskTypeOptions.value[taskTypeIndex.value]
  
  // 如果是"履约出库"类型，需要选择配送仓点
  if (selectedType === '履约出库') {
    if (warehouseIndex.value === '') {
      uni.showToast({
        title: '请选择配送仓点',
        icon: 'none'
      })
      return true
    }
  }
  
  // 检查所有商品的计划出库数量是否超过批次可用库存
  for (const product of productList.value) {
    if (product.batch && product.plannedQuantity > product.batchCount) {
      uni.showToast({
        title: '计划出库数量不能大于批次可用库存',
        icon: 'none'
      })
      return true
    }
  }
  
  return false
})

// 计算属性：检查商品是否有可用的批次选项
const hasAvailableBatches = (product) => {
  const batches = getProductBatchOptions(product)
  return batches.length > 0
}

// 计算属性：检查商品的计划出库数量是否超过批次可用库存
const isQuantityExceedingStock = (product) => {
  return product.batch && product.plannedQuantity > product.batchCount
}

// 计算属性：过滤掉没有可用批次的商品
const filteredProductList = computed(() => {
  return productList.value.filter(product => hasAvailableBatches(product))
})

// 处理任务类型选择变化
const onTaskTypeChange = (e) => {
  taskTypeIndex.value = e.detail.value
  // 当任务类型改变时，重置配送仓点的选择
  const selectedType = taskTypeOptions.value[e.detail.value]
  
  // 重置配送仓点选择
  warehouseIndex.value = ''
  
  // 如果已选择供应商，重新过滤配送仓点；否则清空配送仓点选项
  if (supplierIndex.value !== '') {
    filterWarehousesBySupplier()
  } else {
    warehouseOptions.value = []
  }
}





// 根据选择的供应商过滤配送仓点
const filterWarehousesBySupplier = () => {
  if (supplierIndex.value === '') {
    // 如果没有选择供应商，不显示任何配送仓点
    warehouseOptions.value = []
    return
  }
  
  const selectedSupplier = supplierOptions.value[supplierIndex.value]
  console.log('选择的供应商:', selectedSupplier)
  
  // 过滤配送仓点，只显示包含当前供应商的仓点
  const filteredWarehouses = allDistributionWarehouses.value.filter(warehouse => {
    // 如果配送仓点没有关联供应商，或者关联供应商数组为空，则不显示该仓点
    if (!warehouse.suppliers || warehouse.suppliers.length === 0) {
      return false
    }
    
    // 检查当前供应商是否在关联供应商列表中
    return warehouse.suppliers.includes(selectedSupplier)
  })
  
  console.log('过滤后的配送仓点:', filteredWarehouses)
  
  // 更新配送仓点选项
  warehouseOptions.value = filteredWarehouses.map(item => item.name)
}

// 处理供应商选择变化
const onSupplierChange = (e) => {
  supplierIndex.value = e.detail.value
  
  // 设置选择的供应商rowid
  if (supplierIndex.value !== '' && supplierData.value[supplierIndex.value]) {
    supplierRowid.value = supplierData.value[supplierIndex.value].rowid
    console.log('设置供应商rowid:', supplierRowid.value)
  } else {
    supplierRowid.value = ''
  }
  
  // 当选择供应商后，过滤配送仓点
  filterWarehousesBySupplier()
  
  // 重置配送仓点选择
  warehouseIndex.value = ''
  
  // 清理没有可用批次的商品
  if (productList.value.length > 0) {
    console.log('供应商变化，开始清理没有可用批次的商品')
    
    const beforeCount = productList.value.length
    const productsWithBatches = productList.value.filter(product => {
      const hasBatches = hasAvailableBatches(product)
      if (!hasBatches) {
        console.log(`商品 ${product['6879f59d8371cd243659b75c']} 没有可用批次，将被移除`)
      }
      return hasBatches
    })
    
    if (productsWithBatches.length !== beforeCount) {
      productList.value = productsWithBatches
      console.log(`清理完成：从 ${beforeCount} 个商品减少到 ${productsWithBatches.length} 个商品`)
      
      if (productsWithBatches.length === 0) {
        uni.showToast({
          title: '已清理无可用批次的商品',
          icon: 'none',
          duration: 2000
        })
      }
    }
  }
}

// 处理配送仓点选择变化
const onWarehouseChange = (e) => {
  warehouseIndex.value = e.detail.value
}

// 处理添加商品
const handleAddProduct = () => {
  // 检查是否选择了供应商
  if (supplierIndex.value === '') {
    uni.showToast({
      title: '请先选择供应商',
      icon: 'none'
    })
    return
  }
  
  // 获取当前选择的供应商名称
  const supplierName = supplierOptions.value[supplierIndex.value]
  
  uni.navigateTo({
    url: `/pages/warehouse/outbound/add-product?supplierName=${encodeURIComponent(supplierName)}&supplierRowid=${encodeURIComponent(supplierRowid.value)}`
  })
}

// 获取商品的批次选项（过滤相同供应商、相同商品且可用库存>0的批次）
const getProductBatchOptions = (product) => {
  console.log('=== getProductBatchOptions 被调用 ===')
  console.log('当前供应商索引:', supplierIndex.value)
  console.log('供应商选项:', supplierOptions.value)
  
  if (!product || !supplierOptions.value[supplierIndex.value]) {
    console.log('返回空数组 - 条件不满足:', {
      hasProduct: !!product,
      hasSupplier: !!supplierOptions.value[supplierIndex.value],
      supplierIndex: supplierIndex.value
    })
    return []
  }
  
  const currentSupplier = supplierOptions.value[supplierIndex.value]
  const productName = product['6879f59d8371cd243659b75c']

  console.log('当前供应商:', currentSupplier)
  console.log('商品名称:', productName)
  console.log('批次库存数据总数:', batchInventoryOptions.value.length)
  
  const filteredData = batchInventoryOptions.value
    .filter(item => {
      const itemSupplier = item['68887aba0e18077cf8de4379'] // 供应商名称
      const itemProductName = item['68887b490e18077cf8de438d'] // 商品名称
      const availableStock = item['6891619bf6303e511c9a7720'] || 0 // 可用库存
      
      return itemSupplier === currentSupplier && 
             itemProductName === productName && 
             availableStock > 0
    })
    .map(item => ({
      rowid: item.rowid, // 批次rowid
      batchName: item['68d932b95e094a5d2cebe1ef'], // 批次名称
      batchCount: item['6891619bf6303e511c9a7720'] || 0 // 批次可用库存
    }))
  
  console.log('过滤后的批次数据:', filteredData)
  return filteredData
}

// 获取当前选中批次的索引
const getBatchIndex = (product) => {
  console.log('=== getBatchIndex 被调用 ===')
  console.log('当前商品批次:', product.batch)
  console.log('当前商品批次rowid:', product.batchRowid)
  
  const options = getProductBatchOptions(product)
  console.log('可选批次:', options)
  
  // 优先使用batchRowid匹配，如果没有则退回到batchName匹配
  let index = -1
  if (product.batchRowid) {
    index = options.findIndex(item => item.rowid === product.batchRowid)
  }
  if (index === -1 && product.batch) {
    index = options.findIndex(item => item.batchName === product.batch)
  }
  
  console.log('当前批次在选项中的索引:', index)
  
  return index
}

// 处理批次选择变化
const onBatchChange = (e, product) => {
  console.log('=== onBatchChange 被调用 ===')
  console.log('选择事件详情:', e)
  console.log('当前商品:', product)
  
  const options = getProductBatchOptions(product)
  console.log('可选批次:', options)
  console.log('选中索引:', e.detail.value)
  
  const selectedBatch = options[e.detail.value]
  console.log('选中的批次:', selectedBatch)
  product.batch = selectedBatch.batchName
  product.batchCount = selectedBatch.batchCount
  product.batchRowid = selectedBatch.rowid // 保存批次rowid
}

// 接收从添加商品页面返回的选中商品
const receiveSelectedProducts = (selectedProducts) => {
  // 将选中的商品添加到商品列表中
  selectedProducts.forEach(product => {
    // 检查是否已存在相同商品，避免重复添加
    const existingIndex = productList.value.findIndex(item => item.rowid === product.rowid)
    if (existingIndex === -1) {
      // 添加新商品到列表
      productList.value.push(product)
    }
  })
}

// 处理删除商品
const handleDeleteProduct = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该商品吗？',
    success: (res) => {
      if (res.confirm) {
        productList.value.splice(index, 1)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 处理保存任务
const handleSave = async () => {
  // 如果按钮被禁用，直接返回
  if (isSaveDisabled.value) {
    uni.showToast({
      title: '请先完成填写',
      icon: 'none'
    })
    return
  }
  
  // 表单验证
  if (taskTypeIndex.value === '') {
    uni.showToast({
      title: '请选择任务类型',
      icon: 'none'
    })
    return
  }
  
  // 验证供应商
  if (supplierIndex.value === '') {
    uni.showToast({
      title: '请选择供应商',
      icon: 'none'
    })
    return
  }
  
  // 根据任务类型进行相应的验证
  const selectedType = taskTypeOptions.value[taskTypeIndex.value]
  
  // 如果是"履约出库"类型，需要验证配送仓点
  if (selectedType === '履约出库') {
    if (warehouseIndex.value === '') {
      uni.showToast({
        title: '请选择配送仓点',
        icon: 'none'
      })
      return
    }
  }
  
  if (filteredProductList.value.length === 0) {
    uni.showToast({
      title: productList.value.length === 0 ? '请添加商品信息' : '暂无可用批次的商品',
      icon: 'none'
    })
    return
  }

  // 验证所有商品都选择了批次和填写了计划出库数量
  for (const product of filteredProductList.value) {
    if (!product.batchRowid || !product.batch) {
      uni.showToast({
        title: '请为所有商品选择批次',
        icon: 'none'
      })
      return
    }
    if (!product.plannedQuantity || product.plannedQuantity <= 0) {
      uni.showToast({
        title: '请为所有商品填写计划出库数量',
        icon: 'none'
      })
      return
    }
  }

  // 打印表单数据
  const formData = {
    userRowid: userStore.getUserInfo().rowid,
    warehouseCode: userStore.warehouseCode,
    taskType: selectedType,
    supplier: supplierOptions.value[supplierIndex.value] || '',
    supplierRowid: supplierRowid.value, // 添加供应商rowid
    warehouse: warehouseIndex.value !== '' ? warehouseOptions.value[warehouseIndex.value] : '',
    remark: remark.value,
    productsRowids: filteredProductList.value.map(product => ({
      productRowid: product.rowid, // 商品rowid
      batchRowid: product.batchRowid || '', // 批次rowid
      plannedQuantity: product.plannedQuantity || 0 // 计划出库数量
    }))
  }
  await http.post(`https://www.dachen.vip/api/workflow/hooks/${userStore.getWarehouseInfo().gys_ck_create}`, formData)

  console.log('保存的表单数据:', formData)
  
  // 保存逻辑
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  })

taskStore.setPendingTaskUpdate({
  updata: "updata"
})
  
  // 返回上一页
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}


const getBatchInventory = async () => {
  try {
      const res = await callWorkflowListAPI('pckc')
  if(res){
    batchInventoryOptions.value = res.data
    
  }
  } catch (error) {
    console.error('获取批次库存失败:', error)
  }
  
}

// 获取配送仓点
const getDistributionWarehouse = async () => {
  try {
    const res = await callWorkflowListAPI('fymbd')
    if(res && res.data){
      console.log('配送仓点', res.data);
      
      // 添加安全保护，检查关联供应商数据是否存在
      const distributionWarehouses = res.data.map(item => {
        const warehouseName = item['689b2132f23d51578296f9e6'];
        let associatedSuppliers = [];
        
        // 安全地解析关联供应商数据
        try {
          if (item['68819756853d0deec0d8be00']) {
            const supplierData = JSON.parse(item['68819756853d0deec0d8be00']);
            associatedSuppliers = supplierData.map(supplier => supplier.name || supplier['68639102a4471151d6aaa98b'] || '');
          }
        } catch (parseError) {
          console.warn('解析关联供应商数据失败:', parseError, '仓库:', warehouseName);
          associatedSuppliers = [];
        }
        
        return {
          name: warehouseName,
          suppliers: associatedSuppliers
        };
      });
      
      // 存储完整的配送仓点数据（包含关联供应商信息）
      allDistributionWarehouses.value = distributionWarehouses;
      
      // 初始显示所有配送仓点名称
      warehouseOptions.value = distributionWarehouses.map(item => item.name);
      
      console.log('处理后的配送仓点数据:', distributionWarehouses);
    }
  } catch (error) {
    console.error('获取配送仓点失败:', error)
  }
}

// 监听任务更新
watch(() => taskStore.pendingTaskUpdate, async (newTask) => {
  if (newTask) {
    console.log('检测到待更新任务:', newTask)
    productList.value = newTask.map(product => ({
      ...product,
      batch: '', // 商品批次
      batchCount: 0, // 商品批次可用库存
      plannedQuantity: 0, // 计划出库数量
      batchRowid: '' // 批次rowid
    }))

    }
      taskStore.clearPendingTaskUpdate()
})

// 监听计划出库数量变化，自动校验
watch(productList, (newProducts) => {
  newProducts.forEach(product => {
    if (product.batch && product.plannedQuantity > product.batchCount) {
      // 如果计划出库数量超过批次可用库存，可以在这里添加额外的处理逻辑
      console.warn(`商品 ${product.name} 的计划出库数量 ${product.plannedQuantity} 超过批次可用库存 ${product.batchCount}`)
    }
  })
}, { deep: true })

// 监听批次库存数据变化，清理没有可用批次的商品
watch(batchInventoryOptions, (newBatchInventory) => {
  if (newBatchInventory && newBatchInventory.length > 0 && productList.value.length > 0) {
    console.log('批次库存数据更新，开始清理没有可用批次的商品')
    
    // 记录清理前的商品数量
    const beforeCount = productList.value.length
    
    // 过滤掉没有可用批次的商品
    const productsWithBatches = productList.value.filter(product => {
      const hasBatches = hasAvailableBatches(product)
      if (!hasBatches) {
        console.log(`商品 ${product['6879f59d8371cd243659b75c']} 没有可用批次，将被移除`)
      }
      return hasBatches
    })
    
    // 如果有变化，更新商品列表
    if (productsWithBatches.length !== beforeCount) {
      productList.value = productsWithBatches
      console.log(`清理完成：从 ${beforeCount} 个商品减少到 ${productsWithBatches.length} 个商品`)
      
      // 显示提示信息
      if (productsWithBatches.length === 0) {
        uni.showToast({
          title: '已清理无可用批次的商品',
          icon: 'none',
          duration: 2000
        })
      }
    }
  }
})

// 获取供应商
const getSupplier = async () => {
  try {
      const res = await callWorkflowListAPI('gonghuoshang')
  if(res){
    console.log('供应商', res.data);
    
    // 安全地过滤供应商数据
    const filteredSuppliers = res.data.filter(item => {
      try {
       return JSON.parse(userStore.getUserInfo()['68ea18b6470b6cef2f580870']).includes(item.rowid)
      } catch (error) {
        console.log('解析供应商数据失败:', error);
        return false;
      }
    });
    
    // 存储完整的供应商数据（包含rowid）
    supplierData.value = filteredSuppliers;
    
    // 只保存供应商名称用于显示
    supplierOptions.value = filteredSuppliers.map(item => {
      return item['68639102a4471151d6aaa98b']
    });

    console.log('过滤后的供应商', supplierOptions.value);
    
    // 自动设置第一个供应商
    if (filteredSuppliers.length > 0) {
      supplierIndex.value = 0
      supplierRowid.value = filteredSuppliers[0].rowid
      console.log('自动设置第一个供应商:', supplierOptions.value[0], 'rowid:', supplierRowid.value)
    }
    
  }
  } catch (error) {
    console.error('获取供应商失败:', error)
  }
  
}

onLoad(async () => {
  uni.showLoading({
    title: '加载中'
  })
  await getDistributionWarehouse()
  await getSupplier()
  await getBatchInventory()
  uni.hideLoading()
})



</script>

<style lang="scss" scoped>
.create-task-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
  
  .section {
    margin-bottom: 20rpx;
    
    .section-title {
      padding: 30rpx;
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      border-bottom: 1rpx solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .add-product-btn {
        color: #87CEEB;
        border: none;
        font-size: 28rpx;
        
        &.add-product-btn-disabled {
          color: #cccccc;
          pointer-events: none;
        }
      }
    }

    .section-nr{
        background-color: #ffffff;
        border-radius: 10rpx;
        padding: 10rpx;
        margin: 10px;
   .form-item {
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      display: flex;
      align-items: center;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        color: #333333;
        font-size: 28rpx;
        min-width: 140rpx;
      }
      
      .picker {
        flex: 1;
        
        .picker-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .picker-text {
            color: #333333;
            font-size: 28rpx;
          }
          
          .picker-arrow {
            color: #999999;
            font-size: 24rpx;
          }
        }
      }
      
      .input {
        flex: 1;
        color: #333333;
        font-size: 28rpx;
        
        &::placeholder {
          color: #999999;
        }
      }
    }
    }
    
 
    
    .empty-products {
      padding: 60rpx 30rpx;
      text-align: center;
      
      .empty-text {
        color: #999999;
        font-size: 28rpx;
      }
    }
    
    .product-list {
      padding: 20rpx 30rpx;
      
      .product-card {
        background-color: #ffffff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
        

        
        .product-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          
          .product-name {
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
            margin-bottom: 12rpx;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          
          .product-code {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .product-spec {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
          }
          
          .stock-info {
            display: flex;
            flex-direction: column;
            
            .unavailable-stock {
              color: #ff4757;
              font-size: 24rpx;
              margin-bottom: 4rpx;
            }
            
            .available-stock {
              color: #2ed573;
              font-size: 24rpx;
            }
          }
          
          .product-batch-quantity {
            margin-top: 16rpx;
            display: flex;
            flex-direction: column;
            gap: 12rpx;
            
            .batch-input-wrapper,
            .quantity-input-wrapper {
              display: flex;
              align-items: center;
              gap: 12rpx;
            }
            
            .quantity-input-container {
              flex: 1;
              display: flex;
              flex-direction: column;
              gap: 8rpx;
            }
            
            .batch-label,
            .quantity-label {
              color: #666666;
              font-size: 24rpx;
              min-width: 140rpx;
            }
            
            .batch-picker {
              flex: 1;
            }
            
            .batch-picker .picker-content {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 8rpx 16rpx;
              border: 1rpx solid #e0e0e0;
              border-radius: 8rpx;
              background-color: #fff;
              min-height: 60rpx;
            }
            
            .batch-picker .picker-content.picker-disabled {
              background-color: #f5f5f5;
              border-color: #d0d0d0;
            }
            
            .batch-picker .picker-text {
              font-size: 24rpx;
              color: #333;
            }
            
            .batch-picker .picker-text.picker-text-disabled {
              color: #999;
            }
            
            .batch-picker .picker-arrow {
              font-size: 24rpx;
              color: #999;
            }
            
            .batch-picker .picker-arrow.picker-arrow-disabled {
              color: #ccc;
            }
            
            .batch-tip {
              margin-top: 8rpx;
              padding: 8rpx 0;
            }
            
            .batch-tip-text {
              font-size: 22rpx;
              color: #ff9500;
              line-height: 1.4;
            }
            
            .batch-stock-info {
              display: flex;
              align-items: center;
              gap: 12rpx;
              margin-top: 8rpx;
              padding: 8rpx 0;
            }
            
            .batch-stock-label {
              color: #666666;
              font-size: 24rpx;
              min-width: 140rpx;
            }
            
            .batch-stock-value {
              color: #2ed573;
              font-size: 24rpx;
              font-weight: bold;
            }
            
            .quantity-input {
              flex: 1;
              padding: 8rpx 16rpx;
              border: 1rpx solid #e0e0e0;
              border-radius: 8rpx;
              font-size: 24rpx;
              color: #333333;
              background-color: #f8f8f8;
              
              &::placeholder {
                color: #999999;
              }
              
              &.quantity-input-error {
                border-color: #ff4757;
                background-color: #fff5f5;
              }
            }
            
            .quantity-error-tip {
              margin-top: 4rpx;
            }
            
            .quantity-error-text {
              font-size: 22rpx;
              color: #ff4757;
              line-height: 1.4;
            }
          }
        }
        
        .product-actions {
          display: flex;
          flex-direction: column;
          gap: 16rpx;
          
          .delete-btn {
            padding: 10rpx 20rpx;
            border-radius: 8rpx;
            font-size: 24rpx;
            border: none;
            min-width: 80rpx;
            background-color: #ff4757;
            color: #ffffff;
          }
        }
      }
      
      .empty-state {
        padding: 100rpx 0;
        text-align: center;
        
        .empty-text {
          color: #999999;
          font-size: 28rpx;
        }
      }
    }
  }
  
  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    padding: 30rpx;
    box-shadow: 0 -2rpx 4rpx rgba(0, 0, 0, 0.1);
    
    .save-btn {
      width: 100%;
      background: linear-gradient(to right, #48eceb, #0fcee9);
      color: #ffffff;
      border: none;
      border-radius: 32rpx;
      font-size: 32rpx;
      font-weight: bold;
      
      &.save-btn-disabled {
        background: #cccccc !important;
        color: #999999 !important;
        cursor: not-allowed;
        opacity: 0.6;
      }
    }
  }
}
</style>